﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data.Linq;
using System.Text;
using ModelLayer;

namespace DAL
{
    public class TokenDB
    {
        public TokenDB()
        {

        }   

        public ModelLayer.Token CreateToken(int userId, string tokenId, int expire)
        {
            using (var db = new BalderDataContext())
            {
                Token token = new Token();
                ModelLayer.Token t = new ModelLayer.Token();

                token.UserId = userId;
                token.TokenId = tokenId;
                token.Expire = expire;

                db.Tokens.InsertOnSubmit(token);
                db.SubmitChanges();
                t.Expire = token.Expire;
                t.TokenId = token.TokenId;
                t.UserId = token.UserId;
                return t;
            }
        }

        public ModelLayer.Token FindToken(int userid)
        {
            ModelLayer.Token token = new ModelLayer.Token();
            using (var db = new BalderDataContext())
            {
                try
                {
                    var t = db.Tokens.Single(x => x.UserId == userid);
                    token.TokenId = t.TokenId;
                    token.UserId = t.UserId;
                    token.Expire = t.Expire;
                }
                catch (Exception)
                {
                    
                    token = new ModelLayer.Token();
                }
                
                
            }
            if (token.TokenId != null)
            {
                return token;
            }
            return null;
        }

         public void DeleteToken(int uid)
         {
             using (var db = new BalderDataContext())
             {
                 
                 var t = db.Tokens.Single(x => x.UserId == uid);
                 Token tok = t;
                 

                 //db.Tokens.Attach(tok);
                 db.Tokens.DeleteOnSubmit(tok);
                 db.SubmitChanges();
             }
         }
    }
}
